// import { outLogin } from '@/services/ant-design-pro/api';
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { Spin,Modal,Form,Input,message,Button } from 'antd';
import { createStyles } from 'antd-style';
import { stringify } from 'querystring';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback,useState } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';
import services from '@/services/home';
const { updatePassWord,logout} =
  services.UserController;
import stylesp from './RightContent.less';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser }:any = initialState || {};
  return <span className="anticon">{currentUser?.nickName}{currentUser?.jobNumber ? `(${currentUser?.jobNumber})`:''}</span>;
};

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
  };
});


export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu, children }) => {
  const { clearAllGlobal } = useModel('global');
  const { initialState, setInitialState }:any = useModel('@@initialState');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loadingPwd, setLoadingPwd] = useState(false);
  const [formUpPwd] = Form.useForm();
  const { currentUser }:any = initialState || {};

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const handleOk =  (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    setLoadingPwd(true);
    formUpPwd.validateFields().then(async (values:any) => {
      const _res = await updatePassWord({
        username:initialState?.currentUser?.mail,
        passWord: values?.password,
        newPassWord:values.newPassWord
      });
      setLoadingPwd(false);
      console.log('values==',_res,values);
      if(_res.appCode == 'S0000'){
        message.success('修改成功');
        setIsModalOpen(false);
        // history.push('/');
      }else{
        message.error(_res.appMesg || '失败，请重试');
      }
    })
    .catch((errorInfo:any) => {
      setLoadingPwd(false);
      // console.log('errorInfo==',errorInfo);
    });
    // setIsModalOpen(false);
 
  };

  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    setIsModalOpen(false);
  };


  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    // await outLogin();
    // const { search, pathname } = window.location;
    // const urlParams = new URL(window.location.href).searchParams;
    // /** 此方法会跳转到 redirect 参数所在的位置 */
    // const redirect = urlParams.get('redirect');
    // // Note: There may be security issues, please note
    // if (window.location.pathname !== '/user/login' && !redirect) {
    //   history.replace({
    //     pathname: '/user/login',
    //     search: stringify({
    //       redirect: pathname + search,
    //     }),
    //   });
    // }
    clearAllGlobal();
    setTimeout(()=>{
      // history.replace('/login');
      window.location.href = window.location.origin+'/login'
    });
  };
  const { styles } = useStyles();

  const onMenuClick = useCallback(
    async (event: MenuInfo) => {
      const { key } = event;
      if (key == 'logout') {
        
        await logout();
        flushSync(() => {
          setInitialState((s:any) => ({ ...s, currentUser: undefined }));
        });
        loginOut();
        return;
      }else if(key == 'updatepwd'){
        setIsModalOpen(true);
      }
      // history.push(`/account/${key}`);
    },
    [setInitialState],
  );

  const loading = (
    <span className={styles.action}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }


  if (!currentUser || !currentUser.nickName) {
    return loading;
  }

  const menuItems = [
    ...(menu
      ? [
          {
            key: 'center',
            icon: <UserOutlined />,
            label: '个人中心',
          },
          {
            key: 'settings',
            icon: <SettingOutlined />,
            label: '个人设置',
          },
          {
            type: 'divider' as const,
          },
        ]
      : []),
    {
        key: 'updatepwd',
        icon: <UserOutlined />,
        label: '修改密码',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <>
      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onMenuClick,
          items: menuItems,
        }}
      >
        {children}
      </HeaderDropdown>
      <Modal
      open={isModalOpen}
      title="修改密码"
      maskClosable={false}
      keyboard={false}
      width={'50%'}
      classNames={{
        body:stylesp.tc_lg_1,
        footer:stylesp.tc_lg_2,
      }}
      onOk={handleOk}
      onCancel={handleCancel}
      footer={[
        <Button key="submit" type="primary" className={stylesp.tc_lg_2_1} loading={loadingPwd} onClick={handleOk}>
          确定
        </Button>
      ]}
    >
      <Form {...formItemLayout} form={formUpPwd} name="form_in_modal" initialValues={{ remember: true }}>
        <Form.Item
          name="password"
          label="旧密码"
          hasFeedback
          rules={[{ required: true, message: '请输入旧密码' }, {
            min: 6,
            message: '至少六位数',
          },]}
        >
          <Input.Password placeholder='请输入旧密码' />
        </Form.Item>
        <Form.Item
          name="newPassWord"
          label="新密码"
          dependencies={['password']}
          hasFeedback
          rules={[
            { required: true, message: '请输入新密码!' }, {
              min: 6,
              message: '至少六位数',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') == value) {
                  return Promise.reject(new Error('您输入的新密码不能和旧密码一样!'));
                }
                return Promise.resolve();
              },
            }),
          ]}
        >
          <Input.Password placeholder='请输入至少6位(不区分大小写)的新密码'/>
        </Form.Item>
        <Form.Item
          name="confirm"
          label="确认新密码"
          dependencies={['newPassWord']}
          hasFeedback
          rules={[
            {
              required: true,
              message: '请再次输入您的新密码!',
            },
            {
              min: 6,
              message: '至少六位数',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassWord') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('您输入的新密码不匹配!'));
              },
            }),
          ]}
        >
          <Input.Password placeholder='请重复输入新密码'/>
        </Form.Item>
      
      
      </Form>
      </Modal>
    </>
  );
};